<template>
	<view class="common-bg">
		<view class="pad-20">
			<uni-nav-bar :statusBar="true" :border="false" left-icon="back" background-color="transparent"
				@clickLeft="clickLeft" :title="$t('deviceShare.deviceShare')">
			</uni-nav-bar>
			<view class="device-box m-t-20 shadow">
				<view class="left">
					<view class="ico">
						<image class="w-100" src="/static/svg/devices.svg" mode="widthFix"></image>
					</view>
					<view class="font-16 font-500 col-000-8">
						{{ deviceDetail.device_name }}
					</view>
				</view>
				<view class="right col-000-4 font-14 font-500">
					<!-- 设备ID: SP001234 -->
					{{ $t('deviceShare.deviceID') }}

				</view>
			</view>
			<view class="share-box m-t-40">
				<view class="font-18 col-000-8 font-600">
					{{ $t('deviceShare.deviceShare') }}
				</view>
				<view class="font-14 col-000-4 m-t-8">
					<!-- 已共享给N位用户 -->
          {{ $t('deviceShare.sharedTo') }}{{ shareList.length }} {{ $t('deviceShare.sharedToCount') }}
				</view>
				<view class="list" v-if="shareList.length > 0">
					<view class="item shadow" v-for="share in shareList" :key="share.share_id">
						<view class="left">
							<view class="avatar">
								<image class="w-100" src="/static/logo.png" mode="widthFix"></image>
							</view>
							<view class="">
								<view class="name font-16 font-500 col-000-8">
									{{ share.shared_user_email || share.shared_user_id }}
								</view>
								<view class="email font-11 col-000-4">
									{{ share.shared_user_email }}
								</view>
								<view class="time font-11 col-000-4">
									{{ $t('deviceShare.sharedAt') }} {{ formatDate(share.create_time) }}
								</view>
							</view>
						</view>
						<view class="right">
							<view class="btn font-11 col-fff flex-center-center" :class="getStatusClass(share.status)">
								{{ getStatusText(share.status) }}
							</view>
							<view class="clear" @click="revokeShare(share)">
								<image class="w-100" src="/static/images/clear.png" mode="widthFix"></image>
							</view>
						</view>
					</view>
				</view>
				<view v-else class="font-14 col-000-4 m-t-20 text-center">
					{{ $t('deviceShare.noShares') }}
				</view>
				<view class="btn-zan"></view>
				<view class="btn-foot flex-center-center" @click="open()">
					<view class="ico">
						<uni-icons type="plusempty" size="20"></uni-icons>
					</view>
					<view class="">
						<!-- 共享设备 -->
						{{ $t('deviceShare.deviceShare') }}

					</view>
				</view>
			</view>
		</view>
		<uni-popup ref="popup_share" type="bottom" border-radius="16px 16px 0 0">
			<view class="pop-box pad-20">
				<view class="flex flex-between flex-center">
					<view class="col-000-8 font-18 font-600">
						<!-- 添加共享用户 -->
						{{ $t('deviceShare.deviceShare') }}
					</view>
					<view class="close" @click="closePopup">
						<uni-icons type="closeempty" color="rgba(0,0,0,0.4)" size="20"></uni-icons>
					</view>
				</view>
				<view class="m-t-40">
					<view class="font-14 col-000-8 font-500">
						<!-- 用户ID或邮箱 -->
						{{ $t('deviceShare.deviceID') }}
					</view>
					<view class="m-t-8">
						<uni-easyinput class="input-box" :inputBorder="false" v-model="userIdentifier" :placeholder="$t('deviceShare.emailPlaceholder')" trim="all" />
					</view>
					<view class="send-btn font-14 col-fff font-500 m-t-40 flex-center-center" @click="sendInvite">
						<!-- 发送邀请 -->
						{{ $t('deviceShare.sendInvitation') }}
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
  import deviceApi from '@/api/device.js';
  import deviceStore from '@/store/deviceStore.js';
	import shareApi from '@/api/share.js';
	
	export default {
		data() {
			return {
				status: 1,
        deviceSn: '',
				deviceId: '',
        deviceDetail: {
					device_name: '',
					sn: '',
					device_status: 0
				},
				shareList: [],
				userIdentifier: '', // 用户名或邮箱
			}
		},
    onLoad(option) {
			const sn = option?.sn || '';
      this.deviceSn = sn;
			if(!sn) {
				uni.showToast({
					title: this.$t('list.device_not_exist'),
					icon: 'none'
				})
				return
			}
			
			console.log(`[DEVICE-SHARE] 使用传递的设备SN: ${this.deviceSn}`);
      this.getDetailBySn(sn);
		},

		created() {
			// created 钩子中不再获取参数
		},
		methods: {
      //通过SN获取设备详情
      async getDetailBySn(sn) {
				try {
					// 先尝试从API获取完整设备信息
					const res = await deviceApi.getDeviceDetail({ sn });
					if (res.errCode === 0 && res.data) {
					this.deviceDetail = res.data;
					this.deviceId = res.data.id || res.data._id;
					console.log(`[DEVICE-SHARE] 获取设备详情成功:`, this.deviceDetail);
					
					// 将设备所有者信息存入 deviceStore
					if (res.data.owner_id !== undefined) {
						const deviceStatus = deviceStore.getDeviceStatus(sn) || {};
						// 将 owner_id 信息存入设备状态
						deviceStore.updateDeviceStatus(sn, {
							...deviceStatus,
							owner_id: res.data.owner_id,
							device_name: res.data.device_name || deviceStatus.device_name
						});
						console.log(`[DEVICE-SHARE] 已更新设备 ${sn} 的 owner_id 信息:`, res.data.owner_id);
					}						// 获取设备分享列表
						await this.loadShareList();
					} else {
						throw new Error('获取设备详情失败');
					}
				} catch (error) {
					console.error('[DEVICE-SHARE] 获取设备详情失败:', error);
					// 降级方案：从缓存获取设备信息
					const deviceStatus = deviceStore.getDeviceStatus(sn);
					if (deviceStatus && deviceStatus.device_name) {
						this.deviceDetail = {
							device_name: deviceStatus.device_name,
							sn: sn,
							device_status: deviceStatus.online ? 1 : 0
						};
					} else {
						this.deviceDetail = {
							device_name: `设备 ${sn}`,
							sn: sn,
							device_status: 0
						};
					}
					
					uni.showToast({
						title: '获取设备详情失败',
						icon: 'none'
					});
				}
      },
			
			// 加载分享列表
			async loadShareList() {
				try {
					if (!this.deviceId) {
						console.warn('[DEVICE-SHARE] deviceId 为空，无法加载分享列表');
						return;
					}
					
					console.log(`[DEVICE-SHARE] 加载设备 ${this.deviceId} 的分享列表`);
					const res = await shareApi.getDeviceShareList({
						deviceId: this.deviceId
					});
					
					if (res.errCode === 0 && res.data) {
						this.shareList = res.data.shares || [];
						console.log(`[DEVICE-SHARE] 加载分享列表成功，共 ${this.shareList.length} 条`);
					} else {
						console.error('[DEVICE-SHARE] 加载分享列表失败:', res);
						this.shareList = [];
					}
				} catch (error) {
					console.error('[DEVICE-SHARE] 加载分享列表异常:', error);
					this.shareList = [];
				}
			},
			
			// 发送分享邀请
			async sendInvite() {
				if (!this.userIdentifier || !this.userIdentifier.trim()) {
					uni.showToast({
						title: this.$t('deviceShare.userIdentifierRequired') || '请输入用户名或邮箱',
						icon: 'none'
					});
					return;
				}
				
				// 验证格式:邮箱或用户名(字母数字下划线,3-20位)
				const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
				const usernameReg = /^[a-zA-Z0-9_]{3,20}$/;
				const isEmail = emailReg.test(this.userIdentifier);
				const isUsername = usernameReg.test(this.userIdentifier);
				
				if (!isEmail && !isUsername) {
					uni.showToast({
						title: this.$t('deviceShare.userIdentifierInvalid') || '用户名或邮箱格式不正确',
						icon: 'none'
					});
					return;
				}
				
				try {
					uni.showLoading({
						title: this.$t('deviceShare.sending') || '发送中...'
					});
					
				// 根据输入类型设置不同的参数
				const shareParams = {
					deviceId: this.deviceId,
					permissions: ['view', 'control'],
					expireDays: 30,
					title: {
						'zh-Hans': `${this.deviceDetail.device_name || '设备'}分享邀请`,
						'en': `${this.deviceDetail.device_name || 'Device'} Share Invitation`
					},
					shareMessage: {
						'zh-Hans': '邀请您使用我的沙画设备',
						'en': 'Invite you to use my sand art device'
					}
				};
				
				// 根据输入类型使用不同的参数字段
				if (isEmail) {
					shareParams.sharedUserEmail = this.userIdentifier;
					console.log(`[DEVICE-SHARE] 发送分享邀请(邮箱): deviceId=${this.deviceId}, email=${this.userIdentifier}`);
				} else {
					// 用户名：同时传递 sharedUsername 和 sharedUserEmail
					shareParams.sharedUsername = this.userIdentifier;
					shareParams.sharedUserEmail = this.userIdentifier; // 兼容后端可能只检查 sharedUserEmail
					console.log(`[DEVICE-SHARE] 发送分享邀请(用户名): deviceId=${this.deviceId}, username=${this.userIdentifier}`);
				}
				
				const res = await shareApi.createShare(shareParams);					uni.hideLoading();
					
					if (res.errCode === 0) {
						uni.showToast({
							title: this.$t('deviceShare.inviteSent') || '邀请已发送',
							icon: 'success'
						});
						
						// 清空输入
						this.userIdentifier = '';
						
						// 关闭弹窗
						this.closePopup();
						
						// 刷新分享列表
						await this.loadShareList();
					} else {
						uni.showToast({
							title: res.errMsg || this.$t('deviceShare.inviteFailed') || '发送失败',
							icon: 'none'
						});
					}
				} catch (error) {
					uni.hideLoading();
					console.error('[DEVICE-SHARE] 发送邀请失败:', error);
					uni.showToast({
						title: error.message || this.$t('deviceShare.inviteFailed') || '发送失败',
						icon: 'none'
					});
				}
			},
			
			// 撤销分享
			async revokeShare(share) {
				uni.showModal({
					title: this.$t('deviceShare.revokeTitle') || '撤销分享',
					content: this.$t('deviceShare.revokeConfirm') || `确定要撤销对 ${share.shared_user_email} 的分享吗？`,
					success: async (modalRes) => {
						if (modalRes.confirm) {
							try {
								uni.showLoading({
									title: this.$t('deviceShare.revoking') || '撤销中...'
								});
								
								console.log(`[DEVICE-SHARE] 撤销分享: deviceId=${this.deviceId}, sharedUserId=${share.shared_user_id}`);
								const res = await shareApi.revokeShare({
									deviceId: this.deviceId,
									sharedUserId: share.shared_user_id,
									revokeReason: '拥有者撤销分享'
								});
								
								uni.hideLoading();
								
								if (res.errCode === 0) {
									uni.showToast({
										title: this.$t('deviceShare.revokeSuccess') || '撤销成功',
										icon: 'success'
									});
									
									// 刷新分享列表
									await this.loadShareList();
								} else {
									uni.showToast({
										title: res.errMsg || this.$t('deviceShare.revokeFailed') || '撤销失败',
										icon: 'none'
									});
								}
							} catch (error) {
								uni.hideLoading();
								console.error('[DEVICE-SHARE] 撤销分享失败:', error);
								uni.showToast({
									title: error.message || this.$t('deviceShare.revokeFailed') || '撤销失败',
									icon: 'none'
								});
							}
						}
					}
				});
      },
			
			// 格式化日期
			formatDate(dateStr) {
				if (!dateStr) return '';
				const date = new Date(dateStr);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			
			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					0: this.$t('deviceShare.statusPending') || '待接受',
					1: this.$t('deviceShare.statusAccepted') || '已接受',
					2: this.$t('deviceShare.statusRejected') || '已拒绝',
					3: this.$t('deviceShare.statusRevoked') || '已撤销',
					4: this.$t('deviceShare.statusExpired') || '已过期'
				};
				return statusMap[status] || '未知';
			},
			
			// 获取状态样式类
			getStatusClass(status) {
				const classMap = {
					0: 'wait',      // 待接受 - 黄色
					1: '',          // 已接受 - 绿色（默认）
					2: 'rejected',  // 已拒绝 - 灰色
					3: 'revoked',   // 已撤销 - 灰色
					4: 'expired'    // 已过期 - 灰色
				};
				return classMap[status] || '';
			},
			clickLeft() {
				uni.navigateBack()
			},
			open() {
				this.$refs.popup_share.open('bottom')
			},
			closePopup() {
				this.$refs.popup_share.close()
			},
		}
	}
</script>

<style lang="scss" scoped>
	.list {
		width: 100%;
		margin-top: 40rpx;
		.item {
			width: 100%;
			margin-bottom: 32rpx;
			padding: 32rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			.left {
				display: flex;
				align-items: center;
				justify-content: flex-start;
			}
			.right {
				display: flex;
				align-items: center;
				justify-content: flex-end;
			}
			.avatar {
				width: 76rpx;
				height: 76rpx;
				border-radius: 100%;
				overflow: hidden;
				margin-right: 32rpx;
			}
			.btn {
				width: 106rpx;
				height: 48rpx;
				background-color: #30A44F;
				border-radius: 24rpx;
				margin-right: 32rpx;
				&.wait {
					background-color: #FABD18;
				}
				&.rejected, &.revoked, &.expired {
					background-color: #999999;
				}
			}
			.clear {
				width: 40rpx;
				height: 40rpx;
				opacity: 0.4;
			}
		}
	}
	.device-box {
		width: 100%;
		height: 140rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 32rpx;
		.left {
			display: flex;
			align-items: center;
			justify-content: flex-start;
		}
		.ico {
			width: 48rpx;
			height: 48rpx;
			margin-right: 40rpx;
		}
	}
	.btn-zan {
		width: 100%;
		height: 144rpx
	}
	.btn-foot {
		height: 100rpx;
		border-radius: 16rpx;
		border: 2rpx solid rgba(0,0,0,0.8);
		background-color: #fff;
		position: fixed;
		left: 40rpx;
		right: 40rpx;
		bottom: 44rpx;
		.ico {
			width: 40rpx;
			height: 40rpx;
			margin-right: 16rpx;
		}
	}
	.pop-box {
		width: 100%;
		background-color: #F3F3F3;
		border-top-left-radius: 32rpx;
		border-top-right-radius: 32rpx;
		.send-btn {
			width: 670rpx;
			height: 100rpx;
			background: #000000;
			border-radius: 16rpx;
		}
		.input-box {
			width: 99%;
			border-radius: 8rpx;
			border: 2rpx solid rgba(0,0,0,0.8);
			overflow: hidden;
		}
	}
</style>